package com.group15.phms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.group15.phms.AddNewDialogFragment.AddNewDialogListener;
import com.group15.phms.DeleteDialogFragment.DeleteDialogListener;

import android.os.Bundle;
import android.app.DialogFragment;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.support.v4.app.NavUtils;

public class ContactInfo extends ListActivity implements DeleteDialogListener, AddNewDialogListener{
	SharedPreferences logins;
	DatabaseHelper db;
	SimpleAdapter adapter;
	String currentUser;
	ArrayList<Map<String, String>> data;
	ListView ItemList;
	List<Contact> contacts;
	String deleteContactName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact_info);
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		db= new DatabaseHelper(getApplicationContext());
		
		findViewById(R.id.doctorInfoTable).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						doctorInfo();
					}
				});
		findViewById(R.id.personalInfoTable).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						userInfo();
					}
				});
		
		contacts = db.getContacts(currentUser);
		db.closeDB();
		data = new ArrayList<Map<String, String>>();
		for (Contact c : contacts) {
		    Map<String, String> datum = new HashMap<String, String>(3);
		    datum.put("name", c.getName());
		    datum.put("email", c.getEmail());
		    datum.put("phone", c.getPhone());
		    data.add(datum);
		}
		
		
		adapter = new SimpleAdapter(this, data,
                                      R.layout.contact_row,
                                      new String[] {"name", "email", "phone"},
                                      new int[] {R.id.toptext,
                                                 R.id.centertext,
                                                 R.id.bottomtext});
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		
		this.getListView().setLongClickable(true);
		this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
		    public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
		    	DialogFragment f = new DeleteDialogFragment();
		        f.show(getFragmentManager(), "DeleteDialogFragment");
		        deleteContactName = contacts.get(position).getName();
		        return true;
		    }
		});
	}

	@Override
	public void onRestart()
	{
		super.onRestart();
		db= new DatabaseHelper(getApplicationContext());
		contacts = db.getContacts(currentUser);
		db.closeDB();
		data = new ArrayList<Map<String, String>>();
		for (Contact c : contacts) {
		    Map<String, String> datum = new HashMap<String, String>(3);
		    datum.put("name", c.getName());
		    datum.put("email", c.getEmail());
		    datum.put("phone", c.getPhone());
		    data.add(datum);
		}
		adapter = new SimpleAdapter(this, data,
                                      R.layout.contact_row,
                                      new String[] {"name", "email", "phone"},
                                      new int[] {R.id.toptext,
                                                 R.id.centertext,
                                                 R.id.bottomtext});
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.contact_info, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			intent = new Intent(this, Login.class);
	    	startActivity(intent);
	    	finish();
			return true;
		case R.id.action_search:
			intent = new Intent(this, Search.class);
	    	startActivity(intent);
			return true;
		case R.id.editbutton:
			editFields();
			return true;
		case R.id.addbutton:
			DialogFragment f = new AddNewDialogFragment();
	        f.show(getFragmentManager(), "AddDoseDialogFragment");
            return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	//delete a contact
	@Override
	public void onPositiveClick()
	{
		db= new DatabaseHelper(getApplicationContext());
		db.deleteContact(deleteContactName, currentUser);
		Toast.makeText(getApplicationContext(),"Contact deleted successfully", Toast.LENGTH_SHORT).show();
		contacts = db.getContacts(currentUser);
		data = new ArrayList<Map<String, String>>();
		for (Contact c : contacts) {
		    Map<String, String> datum = new HashMap<String, String>(3);
		    datum.put("name", c.getName());
		    datum.put("email", c.getEmail());
		    datum.put("phone", c.getPhone());
		    data.add(datum);
		}
		adapter = new SimpleAdapter(this, data,
                                      R.layout.contact_row,
                                      new String[] {"name", "email", "phone"},
                                      new int[] {R.id.toptext,
                                                 R.id.centertext,
                                                 R.id.bottomtext});
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		adapter.notifyDataSetChanged();
		db.closeDB();
	}
	
	//add new Contact
	@Override
	public void onPositiveClick(View view) {
		db= new DatabaseHelper(getApplicationContext());
		String name = ((EditText) view.findViewById(R.id.name)).getText().toString();
 	    String email = ((EditText) view.findViewById(R.id.email)).getText().toString();
 	    String phone = ((EditText) view.findViewById(R.id.phone)).getText().toString();
 	    Contact con = new Contact(name, email, phone);
 	    String exception = db.addContact(con, currentUser);
 	    contacts = db.getContacts(currentUser);
		data = new ArrayList<Map<String, String>>();
		for (Contact c : contacts) {
		    Map<String, String> datum = new HashMap<String, String>(3);
		    datum.put("name", c.getName());
		    datum.put("email", c.getEmail());
		    datum.put("phone", c.getPhone());
		    data.add(datum);
		}
		adapter = new SimpleAdapter(this, data,
                                     R.layout.contact_row,
                                     new String[] {"name", "email", "phone"},
                                     new int[] {R.id.toptext,
                                                R.id.centertext,
                                                R.id.bottomtext});
		ListView itemList=(ListView)findViewById(android.R.id.list);
		itemList.setAdapter(adapter);
		itemList.setEmptyView(findViewById(R.id.empty));
		adapter.notifyDataSetChanged();
		db.closeDB();
		if (exception.equals("success"))
			Toast.makeText(getApplicationContext(),"Contact added successfully", Toast.LENGTH_SHORT).show();
		else
			Toast.makeText(getApplicationContext(),"Contact NOT added.\nName already exists.", Toast.LENGTH_LONG).show();
	}
	
	void editFields()
	{
		
	}
	void userInfo()
	{
		Intent intent=new Intent(this, UserInfo.class);
		startActivity(intent);
		finish();
	}
	void doctorInfo()
	{
		Intent intent=new Intent(this, DoctorInfo.class);
		startActivity(intent);
		finish();
	}
	

}
